#include "./draw_task.h"
#include "../ice_driver/sensor.h"
#include "../ice_driver/ctrl.h"

namespace ice_task {

using namespace ice_driver;

DrawTask drawTask;

void DrawTask::init_start() {
    m_flags.init();
    m_mq.init();
    start();
}

void DrawTask::run() {

    for (;;) {
        switch (m_mode) {
            case Mode::IDLE: do_idle(); break;
            case Mode::WORK: do_work(); break;
            case Mode::TIMEOUT: do_timeout(); break;
            case Mode::STOP: do_stop(); break;
        }
    }
}

void DrawTask::do_idle() {

    for (;;) {

        if (!sensor.is_bucket_high()) {
            m_mode = Mode::WORK;
            break;
        } 

        if (wait(1000)) {
            break;
        }
    }
}

void DrawTask::do_work() {

    uint32_t time_count = 0;

    ctrl.open(Ctrl::Parts::PUMP);
    for (;;) {
        if (sensor.is_bucket_high()) {
            m_mode = Mode::IDLE;
            break;
        }

        if (wait(1000)) {
            break;
        }
        
        time_count += 1000;
        if (time_count >= DRAW_TIMEOUT) {
            m_mode = Mode::TIMEOUT;
            break;
        }
    }
    ctrl.close(Ctrl::Parts::PUMP);
}

void DrawTask::do_timeout() {
    wait();
}

void DrawTask::do_stop() {
    m_flags.set_flags(FLAG_STOP);
    wait();
}

}
